package controllers

import (
	"encoding/json"
	"github.com/astaxie/beego/validation"
	"github.com/beego/beego/v2/core/logs"
	"github.com/beego/beego/v2/server/web"
	"rate/common/consts"
	"rate/common/res"
	"rate/common/util/cache"
	"rate/common/util/message"
	"rate/common/util/secret"
	"rate/common/util/seqUtils"
	"rate/models"
	"rate/pojo/ao"
	"strconv"
)

type MemberController struct {
	web.Controller
}

// Register 会员注册
// @router / [POST]
// 1. 获取参数
// 2. 邮箱验证
// 3. 注册验证
// 4. 注册
func (req *MemberController) Register() {

	var member ao.MemberAo
	if err := json.Unmarshal(req.Ctx.Input.RequestBody, &member); err != nil {
		logs.Error("参数获取错误,%s", err.Error())
		res.SystemFail(&req.Controller)
	}
	// 参数验证
	valid := validation.Validation{}
	if b, err := valid.Valid(&member); err != nil {
		res.SystemFail(&req.Controller)
	} else if !b {
		res.Result(&req.Controller, consts.ParamError, valid.Errors[0].Message, nil)
	}

	// 验证邮箱
	if bo := validEmail(member); !bo {
		res.Fail(&req.Controller, consts.EmailCodeError)
		req.StopRun()
	}
	// 注册
	m, err := models.CreateMemberWithAo(member)
	if err != nil {
		res.Fail(&req.Controller, err.Error())
	}

	// 自动登录
	token := secret.Md5(strconv.FormatInt(seqUtils.GetSnow(), 10))
	cache.SetToken(token, *m)
	res.Success(&req.Controller, token)
}

// SendRegisterCode 发送邮箱验证码
// @router /code [get]
func (req *MemberController) SendRegisterCode() {
	email := req.GetString("email")
	member := ao.MemberAo{
		Name: email,
	}

	// 参数验证
	valid := validation.Validation{}
	if b, err := valid.Valid(&member); err != nil {
		res.SystemFail(&req.Controller)
	} else if !b {
		res.Result(&req.Controller, consts.ParamError, valid.Errors[0].Message, nil)
	}
	// 发送验证码
	sendMessage(email)
	res.Success(&req.Controller, nil)
}

// sendMessage 发送验证码
func sendMessage(email string) {
	// 读取已有验证码
	code := cache.GetRegisterCode(email)
	if code == "" {
		code = seqUtils.GetRandomNum(6)
	}
	message.SendRegister(code, email)
	// 保存验证码
	cache.SetRegisterCode(code, email)
	go models.InsertEmailRecord(code, email)
}

// validEmail 邮箱验证
func validEmail(member ao.MemberAo) bool {
	code := cache.GetRegisterCode(member.Name)
	if code == "" {
		return false
	} else {
		// 验证邮箱验证码
		cache.DelRegisterCode(member.Name)
		return true
	}
}

// Login 会员登录
// @router /login [POST]
func (req *MemberController) Login() {
	var member ao.MemberAo
	if err := json.Unmarshal(req.Ctx.Input.RequestBody, &member); err != nil {
		logs.Error("参数获取错误,%s", err.Error())
		res.SystemFail(&req.Controller)
	}
	// 密码验证
	me, err := models.FindByName(member.Name)
	if err != nil || me == nil || me.Password != secret.Md5(member.Password+
		web.AppConfig.DefaultString("PasswordSecret", "0.0")) {
		res.Fail(&req.Controller, consts.LoginError)
	}

	// 登录
	// 生成token
	token := secret.Md5(strconv.FormatInt(seqUtils.GetSnow(), 10))
	cache.SetToken(token, *me)
	res.Success(&req.Controller, token)
}
